package com.solo.utils;

import java.sql.*;

public class DBUtil {
    // MySQL驱动程序名称java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    private static String driverName = "com.mysql.jdbc.Driver";

    // 三个静态变量是连接MySQL数据库的参数,服务器的地址和数据库、用户名、密码
    private static String dbUrl = "jdbc:mysql://localhost:3306/db_blog?Unicode=true&characterEncoding=UTF-8&useSSL=false";
    private static String dbUserName = "root";
    private static String dbPassword = "264309";


    /**
     * 获得连接数据库的方法getConn()
     *
     * @return
     * @throws Exception
     */
    public static Connection getConn() {
        Connection conn = null;
        try {
            // 加载驱动程序，JVM查找并加载指定的类，也就是加载数据库驱动程序com.mysql.jdbc.Driver
            Class.forName(driverName);
            conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     * @param rs
     * @param ptmt
     * @param conn
     */
    public static void closeConn(ResultSet rs, PreparedStatement ptmt, Connection conn){
        try {
            if (rs != null) {
                rs.close();
            }
            if (ptmt != null) {
                ptmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
